//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package org.jeecg.modules.online.cgreport.service.a;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.config.mybatis.MybatisPlusSaasConfig;
import org.jeecg.modules.online.cgreport.entity.OnlCgreportHead;
import org.jeecg.modules.online.cgreport.service.IOnlCgreportAPIService;
import org.jeecg.modules.online.cgreport.service.IOnlCgreportItemService;
import org.jeecg.modules.online.cgreport.service.IOnlCgreportParamService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service("onlCgreportAPIService")
public class b implements IOnlCgreportAPIService {
    private static final Logger a = LoggerFactory.getLogger(b.class);
    @Autowired
    private c onlCgreportHeadService;
    @Autowired
    private IOnlCgreportItemService onlCgreportItemService;
    @Autowired
    private MybatisPlusSaasConfig mybatisPlusSaasConfig;
    @Autowired
    private ISysBaseAPI sysBaseAPI;
    @Autowired
    private IOnlCgreportParamService onlCgreportParamService;

    public b() {
    }

    public Map<String, Object> getDataById(String id, Map<String, Object> params) {
        return this.getData(id, (String)null, params);
    }

    public Map<String, Object> getDataByCode(String code, Map<String, Object> params) {
        return this.getData((String)null, code, params);
    }

    public Map<String, Object> getData(String id, String code, Map<String, Object> params) {
        OnlCgreportHead var4 = null;
        if (oConvertUtils.isNotEmpty(id)) {
            var4 = (OnlCgreportHead)this.onlCgreportHeadService.getById(id);
        } else if (oConvertUtils.isNotEmpty(code)) {
            LambdaQueryWrapper<OnlCgreportHead> var5 = new LambdaQueryWrapper();
            var5.eq(OnlCgreportHead::getCode, code);
            var4 = (OnlCgreportHead)this.onlCgreportHeadService.getOne(var5);
        }

        if (var4 == null) {
            throw new JeecgBootException("实体不存在");
        } else {
            try {
                String var8 = var4.getCgrSql().trim();
                String var6 = var4.getDbSource();

                //租户
                var8 = tenantSql(var8);

                return this.executeSelectSqlRoute(var6, var8, params, var4.getId());
            } catch (Exception var7) {
                a.error(var7.getMessage(), var7);
                throw new JeecgBootException("SQL执行失败：" + var7.getMessage());
            }
        }
    }

    public Map<String, Object> executeSelectSqlRoute(String dbKey, String sql, Map<String, Object> params, String headId) throws Exception {
        return StringUtils.isNotBlank(dbKey) ? this.onlCgreportHeadService.executeSelectSqlDynamic(dbKey, sql, params, headId) : this.onlCgreportHeadService.executeSelectSql(sql, headId, params);
    }

    //多租户处理
    /**
     select
     from mws_t_chg_fees t1  --必须有别名加空格
     where t1.del_falg=0  and .... --存在from 的租户必须 是from 别名开头
     **/
    public String tenantSql(String baseSql){
        LoginUser usUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        //多租户处理
        StringBuffer sb=new StringBuffer();

        String mainNickSql="";
        int useIndex=0;
        JSONObject sqlWhereObj = new JSONObject();


        String[] bsSql = baseSql.split("\n");
        for (int i = 0; i < bsSql.length; i++) {
            boolean isFrom=false;
            boolean isJoin=false;
            int beginIndex=-1;

            String rowSql=bsSql[i];
            String currSql=rowSql.toLowerCase();

            if(currSql.contains("from ")){
                isFrom=true;
                beginIndex=currSql.indexOf("from ")+5;
            }else if(currSql.contains("inner join ")){
                isJoin=true;
                beginIndex=currSql.indexOf("inner join ")+11;
            }else if(currSql.contains("left join ")){
                isJoin=true;
                beginIndex=currSql.indexOf("left join ")+10;
            }
            if(isFrom){
                int endIndex = currSql.indexOf(" ", beginIndex);
                if(endIndex>0){
                    String ctable=currSql.substring(beginIndex,endIndex);
                    if(!mybatisPlusSaasConfig.ignoreTable(ctable)){
                        //是租户表
                        int index=beginIndex+ctable.length()+1;
                        String nick=currSql.substring(index,currSql.indexOf(" ",index));
                        mainNickSql=" and "+nick+".tenant_id="+(usUser.getRelTenantIds().split(","))[0];
                        sqlWhereObj.put(nick,mainNickSql);
                    }
                }
            }
            if(isJoin){
                int endIndex = currSql.indexOf(" ", beginIndex);
                if(endIndex>0){
                    String ctable=currSql.substring(beginIndex,endIndex);
                    if(!mybatisPlusSaasConfig.ignoreTable(ctable)){
                        //是租户表
                        int index=beginIndex+ctable.length()+1;
                        String nick=currSql.substring(index,currSql.indexOf(" ",index));
                        rowSql=rowSql+" and "+nick+".tenant_id="+(usUser.getRelTenantIds().split(","))[0];
                    }
                }
            }
            if( currSql.trim().contains("where") && currSql.trim().indexOf("where ")<7){
                int p=currSql.indexOf("where ")+6;
                String nickKey = currSql.substring(p, currSql.indexOf(".",p));
                String whereSqlKey = sqlWhereObj.getString(nickKey);
                if(null != whereSqlKey && whereSqlKey.length()>0){
                    rowSql=rowSql+whereSqlKey;
                }
            }
            sb.append(rowSql+"\n");
        }
        return sb.toString();
    }
}
